package com.example.pageradapterdemo;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.example.pageradapterdemo.fragment.SimpleFragment;
import com.example.pageradapterdemo.model.ImageModel;
import com.example.pageradapterdemo.model.NewsDetail;
import com.example.pageradapterdemo.util.Constants;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import pl.droidsonroids.gif.GifImageView;

public class NewsDetailsActivity extends AppCompatActivity {
    private String newsId;
    private WebView webView;
    private TextView tvTitle;
    private TextView tvSource;
    private TextView tvPublishTime;
    private TextView tvFocus;

    public static final String NEWS_CONTENT_URL = "/news/details?newsId={0}";
    private static OkHttpClient okHttpClient;
    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            int what = msg.what;
            switch (what) {
                case 0x001:
                    NewsDetail newsDetail = (NewsDetail) msg.obj;
                    tvTitle.setText(newsDetail.getTitle());
                    tvSource.setText(newsDetail.getSource());
                    tvPublishTime.setText(newsDetail.getPtime());
                    webView.loadDataWithBaseURL(null,newsDetail.getContent(),"text/html", "UTF-8",null);
                    break;
            }
            return false;
        }
    });
    static{
        okHttpClient = new OkHttpClient();
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news_details);

        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setTitle("");

        Bundle bundle = getIntent().getExtras();
        newsId = bundle.getString("newsId");

        tvTitle = findViewById(R.id.tv_title);
        tvSource = findViewById(R.id.tv_source);
        tvPublishTime = findViewById(R.id.tv_publish_time);
        webView = findViewById(R.id.webView);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setSupportZoom(true);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setDomStorageEnabled(true);
        webView.requestFocus();
        webView.getSettings().setUseWideViewPort(true);
        webView.getSettings().setLoadWithOverviewMode(true);
        GifImageView gifImageView = findViewById(R.id.gifView);
        tvFocus = findViewById(R.id.tv_focus);
        tvFocus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvFocus.setVisibility(View.GONE);
                gifImageView.setVisibility(View.VISIBLE);
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (tvFocus.getText().equals("关注")) {
                            tvFocus.setText("已关注");
                            tvFocus.setTextColor(ContextCompat.getColor(NewsDetailsActivity.this,R.color.material_on_background_disabled));
                        }else{
                            tvFocus.setText("关注");
                            tvFocus.setTextColor(getResources().getColor(android.R.color.holo_red_light));

                        }
                        tvFocus.setVisibility(View.VISIBLE);
                        gifImageView.setVisibility(View.GONE);

                    }
                }, 1000);
            }
        });
        



    }

    @Override
    protected void onStart() {
        super.onStart();
        getNewsContent(newsId);
    }

    private void getNewsContent(String newsId){
        String contentUrl = Constants.BASE_API.concat(NEWS_CONTENT_URL).replace("{0}",newsId);
        Request request = new Request.Builder()
                .url(contentUrl)
                .addHeader("app_id",Constants.APP_ID)
                .addHeader("app_secret",Constants.APP_SECRET)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    if (response.body() != null) {
                        String responseText = response.body().string();
                        if (responseText != null && responseText.length() > 0) {
                            JSONObject jsonObject = JSONObject.parseObject(responseText);
                            JSONObject dataJson = jsonObject.getJSONObject("data");
                            if (dataJson != null) {
                                NewsDetail newsDetail = JSONObject.parseObject(dataJson.toString(),NewsDetail.class);
                                String content = newsDetail.getContent();
                                for (ImageModel image : newsDetail.getImages()) {
                                    Log.e("ddd",image.getPosition());
                                    String width = "0";
                                    String height = "0";
                                    StringBuilder imgTabBuilder = new StringBuilder("<img src=\"" + image.getImgSrc() + "\"");
                                    if (!TextUtils.isEmpty(image.getSize())) {
                                        if (image.getSize().contains("*")) {
                                            width = image.getSize().split("\\*")[0];
                                            height = image.getSize().split("\\*")[1];
                                            String style = " style=\"width:" + width + "px;height:" + height + "px;\"";
                                            imgTabBuilder.append(style);
                                        }
                                    }
                                    imgTabBuilder.append("/>");
                                    String divHtml = "<div style=\"text-align:center\">" + imgTabBuilder.toString() + "</>";
                                    content = content.replace(image.getPosition(),divHtml);
                                }
                                newsDetail.setContent(content);
                                Message message = Message.obtain();
                                message.what = 0x001;
                                message.obj = newsDetail;
                                handler.sendMessage(message);
                            }
                        }
                    }
                }
            }
        });
    }
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }
}